package servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import dao.AdminDao;
import dbutil.DBHelper;

public class DelAdminServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JSONObject jsonObject = new JSONObject();
	boolean isSuccess = false;
	Connection conn;
	
	public DelAdminServlet() {
		super();
	}
	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		AdminDao adminDao = null;
		String adminName = null;
		PrintWriter out = response.getWriter();
		
		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			adminDao = new AdminDao();
			adminName = request.getParameter("adminName");
			isSuccess = adminDao.delAdmin(adminName);
			judgeConn();
		} catch (SQLException e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "数据库错误，请联系有关服务人员");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
	}

	// 返回值判断
	private void judgeConn() throws SQLException {
		if(isSuccess) {
			jsonObject.put("retCode", "1");
			conn.commit();
		} else {
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "未知错误，请联系有关服务人员");
			conn.rollback();
		}
		conn.setAutoCommit(true);
	}
	
	public void init() throws ServletException {
	}

}
